<?php
/**
 * Created by PhpStorm.
 * User: ztos
 * Date: 2017/12/13
 * Time: 上午10:46
 */

namespace app\admin\controller;

use app\common\model\ActivityComment;
use app\common\model\Activity as ActivityModel;
use app\common\model\ActivityPeople;
use PHPExcel;
use app\common\behavior\Service;
use app\common\model\WechatUser;

class Activity extends Admin
{
    /**
     * 主页列表
     */
    public function index()
    {
        $search = input('search');
        $type = input('type') == null ? -1 : input('type');
        $map = array(
            'status' => array('gt', -1),
        );

        if ($type != -1) {
            if ($type || $type == 0) {
                $map['status'] = $type;
            }
        }
        if (!empty($search)) {
            $map['name'] = ['like', '%' . $search . '%'];
        }
        $activity = new ActivityModel();
        $list = $activity->where($map)->order('start_time desc')->paginate(12, false, ['query' => request()->param()]);
         foreach ($list as$key =>$value){
             $map=[
                 'activity_id'=>$value['id'],
                 'status'=>['neq',-1]
             ];
             $num = ActivityComment::where($map)->count();
          $list[$key]['comment']= $num;
         }
        int_to_string($list, array(
            'status' => array(0 => "活动取消", 1 => '预报名', 2 => '开始报名'),
        ));

        $this->assign('checkType', $type);
        $this->assign('list', $list);
        $this->assign('search', $search);
        return $this->fetch();
    }
    /*
     * 活动添加
     */
    public function add()
    {
        if (IS_POST) {
            $data = input('');
            $activity = new ActivityModel();
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
            $data['type']=json_encode($data['type']);
            if (empty($data['name'])) {
                return $this->error('活动名字未填');
            }
            if (empty($data['destination_place'])) {
                return $this->error('活动地点未填');
            }
            if ($data['start_time'] == 0) {
                return $this->error('开始时间未填');
            }
            if($data['end_time']==0){
                //进入这个判断时，开始时间已经填写但结束时间未填，默认为开始时间
                $data['end_time']=$data['start_time']+86399;
            }
            if(  $data['start_time']>$data['end_time']){
                return $this->error('开始时间不能大于结束时间！');
            }
            if (empty($data['id'])) {
                unset($data['id']);
                $info = $activity->save($data);
            } else {
                $info = $activity->save($data, ['id' => $data['id']]);
            }
            if ($info) {
                return $this->success("保存成功", Url('Activity/index'));
            } else {
                return $this->error($activity->getError());
            }
        } else {
            $a = array('1' => 'a', '2' => 'b', '3' => 'c', '4' => 'd', '5' => 'e', '6' => 'f', '7' => 'g', '8' => 'h', '9' => 'i', '10' => 'j', '11' => 'k', '12' => 'l', '13' => 'm', '14' => 'n', '15' => 'o');
            $front_pic = array_rand($a, 1);
            $this->assign('front_pic', $front_pic);
            $data = input('');
            if (!isset($data['id'])) {
                $data['id'] = "";
            }
            $msg = ActivityModel::where('id', $data['id'])->find();
            if ($msg) {
                $msg['start_time'] = date('Y-m-d', $msg['start_time']);
                $msg['type'] = json_decode($msg['type']);
            }
            $this->assign('time', date('Y-m-d', time()));
            $this->assign('info', $msg);
//            echo json_encode($msg);
            return $this->fetch();
        }
    }

    /*报名记录*/
    public function recordinfo()
    {
        $id = input('id');
        $search = input('search');
        $map = [
            'activity_id' => $id,
            'status' => ['neq', -1]
        ];
        $activity = ActivityModel::where('id', $id)->find();
        $Commentlist = ActivityComment::where($map)->paginate(12, false, ['query' => request()->param()]);
        $typelist = array();
        $type = json_decode($activity['type']);
        foreach ($type as $value) {
            $name = $value->name;
            $typeid = $value->typeid;
            $num = $value->number;
            $typelist[$typeid] = $name . "(" . $num . ")";
        }
        int_to_string($Commentlist, array('status' => array(0 => "未付款", 1 => "已报名", 2 => "已取消",3 => "退款中"),
            'type_id' => $typelist
        ));
        //echo ExchangeRecord::getLastSql();
        $this->assign('activity_id', $id);
        $this->assign("list", $Commentlist);
        $this->assign('search', $search);
        return $this->fetch();
    }


    /*报名记录*/
    public function recordinfo2()
    {
        $id = input('id');
        $search = input('search');
        $map = [
            'comment_id' => $id,
            'status' => ['neq', -1]
        ];
        $Peoplelist = ActivityPeople::where($map)->paginate(12, false, ['query' => request()->param()]);
        $typelist = array();


        int_to_string($Commentlist, array('status' => array(0 => "未审核", 1 => "审核成功", 2 => "审核失败")

        ));

        //echo ExchangeRecord::getLastSql();
        $this->assign('comment_id', $id);
        $this->assign("list", $Peoplelist);
        $this->assign('search', $search);

        return $this->fetch();
    }

    /*删除报名记录*/
    public function delSign()
    {
        $id = input('id/a');

        $data = [
            'status' => -1
        ];
        $recordinfo = ActivityComment::where(['id' => array('in', $id)])->update($data);
        if ($recordinfo) {

            return $this->success('删除成功');
        } else {
            return $this->error('删除失败', '', ExchangeRecord::getLastSql());
        }

    }


    /*删除报名记录*/
    public function delPeople()
    {
        $id = input('id/a');

        $data = [
            'status' => -1
        ];
        $recordinfo = ActivityPeople::where(['id' => array('in', $id)])->update($data);
        if ($recordinfo) {

            return $this->success('删除成功');
        } else {
            return $this->error('删除失败', '', ExchangeRecord::getLastSql());
        }
    }

    /**
     * 删除商品功能
     */
    public function del()
    {
        $id = input('id/a');
        $data['status'] = '-1';
        $info = ActivityModel::where(['id' => array('in', $id)])->update($data);
        if ($info) {
            return $this->success("删除成功");
        } else {
            return $this->error("删除失败");
        }
    }

    //导出整理数据
    public function _getoutData($data)
    {


        $list = ActivityComment::where(['activity_id' => $data['id'], 'status' => 1])->select();

        $arrylist = array();
        foreach ($list as $value) {
            $value['activity_name'] = isset($value->activity->name) ? $value->activity->name : "";
            $value['start_time'] = isset($value->activity->start_time) ? $value->activity->start_time : "";
            $value['end_time'] = isset($value->activity->end_time) ? $value->activity->end_time : "";
            $value['people'] = isset($value->people) ? $value->people : array();
            $value['activity_number'] = empty($value->activity->activity_number) ? "不限" : $value->activity->activity_number;

            $type = json_decode($value['activity']['type']);
            $type_text = '';
            $type_number = '';
            $type_price = '';

            foreach ($type as $value2) {


                if ($value['type_id'] == $value2->typeid) {
                    $type_text = $value2->name;
                    $type_number = $value2->number;
                    $type_price = $value2->price;
                }
            }
            $map = [
                'id' => $value['id'],
                'activity_name' => $value['activity_name'],
                'start_time' => date('Y-m-d', $value['start_time']),
                'end_time' => date('Y-m-d', $value['end_time']),
                'activity_number' => $value['activity_number'],
                'sgin_time' => date('Y-m-d', $value['create_time']),//报名时间
                'type' => $type_text . '(' . $type_number . ')',
                'price' => $type_price,
                'people_type' => '联系人',
                'name' => $value['name'],
                'mobile' => $value['mobile'],
                'people_card' => '',
                'emergency_contact' => '',
                'remark' => $value['remark']
            ];
            array_push($arrylist, $map);
            foreach ($value->people as $key => $people) {
                $map = [
                    'id' => $value['id'],
                    'activity_name' => $value['activity_name'],
                    'start_time' => date('Y-m-d', $value['start_time']),
                    'end_time' => date('Y-m-d', $value['end_time']),
                    'activity_number' => $value['activity_number'],
                    'sgin_time' => date('Y-m-d', $value['create_time']),//报名时间
                    'type' => $type_text . '(' . $type_number . ')',
                    'price' => $type_price,
                    'people_type' => '出行人' . $key,
                    'name' => $people['name'],
                    'mobile' => $people['mobile'],
                    'people_card' => $people['people_card'],
                    'emergency_contact' => $people['emergency_contact'],
                    'remark' => $value['remark']
                ];
                array_push($arrylist, $map);

            }
        }
        return $arrylist;
    }


    //导出
    public function outexcel()
    {
        $data = input('');

        $out_data = $this->_getoutData($data);
        $ids = [];
        foreach ($out_data as $v) {
            array_push($ids, $v['id']);
        }
        $ids = array_count_values($ids);
        $excel = new PHPExcel();
        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q');
        $celltitle = [
            '订单编号', '活动名称', '开始时间', '结束时间','活动人数', '活动类型', '报名时间', '活动价格', '人员信息', '姓名', '电话', '身份证号', '紧急联系人', '备注'
        ];
        $cellData = array();
        foreach ($out_data as $key => $value) {
            $cellData[$key] = [$value['id'], $value['activity_name'], $value['start_time'],$value['end_time'], $value['activity_number'], $value['type'], $value['sgin_time'], $value['price'], $value['people_type'], $value['name'], $value['mobile'], $value['people_card'], $value['emergency_contact'], $value['remark']];
        }


        //清空要合并的首行单元格值，用于填充合并后的单元格值
        //$objPHPExcel->getActiveSheet()->setCellValue($column_index.''.$beginRow,'');
        //合并单元格
        // $objPHPExcel->getActiveSheet()->mergeCells('A1:F1');
        $excel->getActiveSheet()->getRowDimension(1)->setRowHeight(30);
        $excel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('K')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('L')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('M')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('N')->setWidth(15);
        $excel->getActiveSheet()->getRowDimension(1)->setRowHeight(35);
        $excel->getActiveSheet()->getRowDimension(2)->setRowHeight(22);
        $excel->getActiveSheet()->getRowDimension(3)->setRowHeight(20);
        //设置字体样式
        $excel->getActiveSheet()->getStyle('A1:N1')->getFont()->setName('黑体');
        $excel->getActiveSheet()->getStyle('A1:N1')->getFont()->setSize(15);
        $excel->getActiveSheet()->getStyle('A1:N1')->getFont()->setBold(true);
        $excel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);


        for ($i = 0; $i < count($celltitle); $i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$celltitle[$i]");
        }
        $data = $cellData;

        $mer = array();//合并开始行数
        //填充表格信息
        for ($i = 2; $i <= count($data) + 1; $i++) {
            $j = 0;
            foreach ($data[$i - 2] as $key => $value) {
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i", "$value");
                $j++;
            }
            // $data[$i-2][$k] ,$k为单行（人员信息）固定位置若要改动导出数据字段则要根据实际情况改动 $k 的值
            if ($data[$i - 2][8] == "联系人") {
                $map = [
                    'id' => $data[$i - 2][0],
                    'index' => $i,
                ];
                array_push($mer, $map);
            }

        }
        //要向下合并的单元格 列名
        $he = array('A', 'B', 'C', 'D', 'E', 'F','H','G','N');
        //开始合并单元格
        foreach ($mer as $value) {
            $num = $ids[$value['id']];
            $index = $value['index'];
            foreach ($he as $h) {
                /*for ($i=  $value['index']+1;$i< $value['index']+1+$num;$i++){
               $excel->getActiveSheet()->setCellValue($h.($index+1).':'. $h.($index+1+$i), '');

                }*/
                $excel->getActiveSheet()->mergeCells($h . ($index) . ':' . $h . ($index + $num-1));

            }

        }




        //清空要合并的首行单元格值，用于填充合并后的单元格值
        //$objPHPExcel->getActiveSheet()->setCellValue($column_index.''.$beginRow,'');
        //合并单元格
        // $objPHPExcel->getActiveSheet()->mergeCells('A1:F1');


        //return json_encode($mer);
        //创建Excel输入对象
        $write = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename="活动报名导出表格.xls"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');

    }


    public function change()
    {
        $data = input('');
        $activity = new ActivityModel();
        //开始报名
        if ($data['type'] == 1) {
            $result = $activity->where('id', $data['id'])->update(['status' => 2]);
            if ($result) {
                return $this->success('开始报名成功');

            } else {
                return $this->error("开始报名失败");

            }
        } //取消报名
        elseif ($data['type'] == 2) {
            if (empty($data['reply'])) {
                return $this->error('取消原因未填');
            }
            $map = ['status' => 0,
                'reply' => $data['reply']
            ];
            $result = $activity->where('id', $data['id'])->update($map);

            if ($result) {
                return $this->success('取消活动成功');

            } else {
                return $this->error("取消活动失败");

            }
        }
    }


}